import { defineStore } from 'pinia'
import { useUserAuthStore } from './userAuth'

export const useMenuStore = defineStore('menu', {
  state: () => ({
    // 菜单数据
    menuData: [],
    // 当前激活的菜单项
    activeMenu: '',
    // 菜单是否折叠
    isCollapsed: false,
    // 菜单加载状态
    loading: false,
    // 菜单权限缓存
    menuPermissions: new Map()
  }),

  getters: {
    // 根据用户权限过滤的菜单
    filteredMenus: (state) => {
      const userAuthStore = useUserAuthStore()
      const userType = userAuthStore.userType
      const permissions = userAuthStore.permissions

      return state.menuData.filter(menu => {
        // 检查角色权限
        if (menu.roles && !menu.roles.includes(userType)) {
          return false
        }
        
        // 检查具体权限
        if (menu.permission && !permissions.includes(menu.permission)) {
          return false
        }
        
        // 检查多个权限（任一满足即可）
        if (menu.permissions && !menu.permissions.some(p => permissions.includes(p))) {
          return false
        }
        
        // 如果有子菜单，递归过滤
        if (menu.children && menu.children.length > 0) {
          menu.children = menu.children.filter(child => {
            if (child.roles && !child.roles.includes(userType)) {
              return false
            }
            if (child.permission && !permissions.includes(child.permission)) {
              return false
            }
            if (child.permissions && !child.permissions.some(p => permissions.includes(p))) {
              return false
            }
            return true
          })
          // 如果子菜单全部被过滤掉，且父菜单没有path，则隐藏父菜单
          if (menu.children.length === 0 && !menu.path) {
            return false
          }
        }
        
        return true
      })
    },

    // 扁平化的菜单列表（用于面包屑等）
    flatMenus: (state) => {
      const flatten = (menus, result = []) => {
        menus.forEach(menu => {
          result.push(menu)
          if (menu.children && menu.children.length > 0) {
            flatten(menu.children, result)
          }
        })
        return result
      }
      return flatten(state.menuData)
    },

    // 获取面包屑路径
    breadcrumbs: (state) => (currentPath) => {
      const findPath = (menus, path, result = []) => {
        for (const menu of menus) {
          if (menu.path === path) {
            return [...result, menu]
          }
          if (menu.children && menu.children.length > 0) {
            const found = findPath(menu.children, path, [...result, menu])
            if (found) return found
          }
        }
        return null
      }
      return findPath(state.menuData, currentPath) || []
    }
  },

  actions: {
    // 初始化菜单数据
    async initMenuData() {
      this.loading = true
      try {
        // 这里可以从API获取菜单数据，现在使用静态数据
        const menuData = [
          {
            key: 'home',
            icon: '🏠',
            label: '首页',
            path: '/',
            roles: ['user', 'lawyer', 'admin'],
            order: 1
          },
          {
            key: 'consultation',
            icon: '💬',
            label: '法律咨询',
            path: '/messages',
            roles: ['user', 'lawyer', 'admin'],
            order: 2
          },
          {
            key: 'case-management',
            icon: '📁',
            label: '案件管理',
            path: '/case',
            permission: 'case:manage',
            roles: ['user', 'lawyer', 'admin'],
            order: 3,
            children: [
              {
                key: 'case-list',
                icon: '📋',
                label: '案件列表',
                path: '/case/list',
                permission: 'case:list',
                roles: ['user', 'lawyer', 'admin']
              },
              {
                key: 'case-create',
                icon: '➕',
                label: '创建案件',
                path: '/case/create',
                permission: 'case:create',
                roles: ['user', 'lawyer']
              },
              {
                key: 'case-analysis',
                icon: '📊',
                label: '案件分析',
                path: '/case/analysis',
                permission: 'case:analysis',
                roles: ['lawyer', 'admin']
              }
            ]
          },
          {
            key: 'lawyer-services',
            icon: '👨‍💼',
            label: '律师服务',
            roles: ['user', 'lawyer', 'admin'],
            order: 4,
            children: [
              {
                key: 'lawyer-team',
                icon: '👥',
                label: '律师团队',
                path: '/lawyer-team',
                roles: ['user', 'lawyer', 'admin']
              },
              {
                key: 'lawyer-center',
                icon: '⚖️',
                label: '律师中心',
                path: '/lawyer-center',
                permission: 'lawyer:center',
                roles: ['lawyer', 'admin']
              },
              {
                key: 'appointment',
                icon: '📅',
                label: '预约咨询',
                path: '/appointment',
                roles: ['user', 'lawyer']
              }
            ]
          },
          {
            key: 'resources',
            icon: '📚',
            label: '法律资源',
            roles: ['user', 'lawyer', 'admin'],
            order: 5,
            children: [
              {
                key: 'legal-resource',
                icon: '📖',
                label: '法律资料',
                path: '/legal-resource',
                roles: ['user', 'lawyer', 'admin']
              },
              {
                key: 'legal-news',
                icon: '📰',
                label: '法律资讯',
                path: '/legal-news',
                roles: ['user', 'lawyer', 'admin']
              },
              {
                key: 'legal-templates',
                icon: '📄',
                label: '法律文书模板',
                path: '/legal-templates',
                permission: 'template:view',
                roles: ['lawyer', 'admin']
              }
            ]
          },
          {
            key: 'system',
            icon: '⚙️',
            label: '系统管理',
            permission: 'system:manage',
            roles: ['admin'],
            order: 6,
            children: [
              {
                key: 'user-management',
                icon: '👤',
                label: '用户管理',
                path: '/system/users',
                permission: 'user:manage',
                roles: ['admin']
              },
              {
                key: 'role-management',
                icon: '🔐',
                label: '角色权限',
                path: '/system/roles',
                permission: 'role:manage',
                roles: ['admin']
              },
              {
                key: 'system-settings',
                icon: '🔧',
                label: '系统设置',
                path: '/system/settings',
                permission: 'system:settings',
                roles: ['admin']
              }
            ]
          },
          {
            key: 'contact',
            icon: '📞',
            label: '联系我们',
            path: '/contact-us',
            roles: ['user', 'lawyer', 'admin'],
            order: 7
          }
        ]

        // 按order排序
        this.menuData = menuData.sort((a, b) => a.order - b.order)
        
        // 缓存菜单权限
        this.cacheMenuPermissions()
        
      } catch (error) {
        console.error('初始化菜单数据失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 缓存菜单权限
    cacheMenuPermissions() {
      const userAuthStore = useUserAuthStore()
      const permissions = userAuthStore.permissions
      const userType = userAuthStore.userType

      const cachePermissions = (menus) => {
        menus.forEach(menu => {
          const key = `${menu.key}-${userType}`
          const hasPermission = this.checkMenuPermission(menu, permissions, userType)
          this.menuPermissions.set(key, hasPermission)
          
          if (menu.children && menu.children.length > 0) {
            cachePermissions(menu.children)
          }
        })
      }

      cachePermissions(this.menuData)
    },

    // 检查菜单权限
    checkMenuPermission(menu, permissions, userType) {
      // 检查角色权限
      if (menu.roles && !menu.roles.includes(userType)) {
        return false
      }
      
      // 检查具体权限
      if (menu.permission && !permissions.includes(menu.permission)) {
        return false
      }
      
      // 检查多个权限（任一满足即可）
      if (menu.permissions && !menu.permissions.some(p => permissions.includes(p))) {
        return false
      }
      
      return true
    },

    // 设置当前激活的菜单
    setActiveMenu(key) {
      this.activeMenu = key
    },

    // 切换菜单折叠状态
    toggleCollapsed() {
      this.isCollapsed = !this.isCollapsed
    },

    // 设置菜单折叠状态
    setCollapsed(collapsed) {
      this.isCollapsed = collapsed
    },

    // 根据路径查找菜单项
    findMenuByPath(path) {
      const find = (menus) => {
        for (const menu of menus) {
          if (menu.path === path) {
            return menu
          }
          if (menu.children && menu.children.length > 0) {
            const found = find(menu.children)
            if (found) return found
          }
        }
        return null
      }
      return find(this.menuData)
    },

    // 刷新菜单权限
    refreshMenuPermissions() {
      this.cacheMenuPermissions()
    }
  }
}) 